package com.travel.servlet;

import java.io.IOException;
import java.util.ArrayList;
import java.util.List;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.logging.log4j.LogManager;
import org.apache.logging.log4j.Logger;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

import com.travel.entities.SpotEntity;

public class SpotServlet extends HttpServlet {

	private static final long serialVersionUID = 1L;

	private static final Logger LOGGER = LogManager.getLogger(SpotServlet.class);

	@Override
	protected void doGet(HttpServletRequest request, HttpServletResponse response)
			throws ServletException, IOException {
		String spotList = request.getParameter("collectedData");
		List<SpotEntity> spotList1 = new ArrayList<SpotEntity>();
		try {
			JSONArray jsonArray = new JSONArray(spotList);
			for (int i = 0; i < jsonArray.length(); i++) {
				if (jsonArray.get(i).equals(null)) {
					continue;
				}
				JSONObject jo = (JSONObject) jsonArray.get(i);
				SpotEntity se = new SpotEntity();
				se.setAddress(jo.getString("address"));
				se.setDetailUrl(jo.getString("detailUrl"));
				se.setProvince(jo.getString("province"));
				se.setTitle(jo.getString("title"));
				se.setUid(jo.getString("uid"));
				se.setUrl(jo.getString("url"));
				spotList1.add(se);
			}
		} catch (JSONException e) {
			LOGGER.error(e.getLocalizedMessage(), e);
		}

		response.setCharacterEncoding("utf-8");
		response.getWriter().append("来信已收到。正在处理...");
	}

	@Override
	protected void doPost(HttpServletRequest request, HttpServletResponse response)
			throws ServletException, IOException {
		doGet(request, response);
	}
}
